package com.gimi.cloud.jimi.common.utils;

import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 为API提供的模拟http请求工具类
 * 
 * @author lilinfeng
 */
public class APIHttpClientUtil {
	private final static String IP = "http://127.0.0.1:8999";
	public final static String SERVICE_URL = "/p2p-api/service";
	
	public static String getToken() {
		Gson gson = new Gson();
		Map<String, Object> paramMap = new HashMap<>();
		Map<String, Object> head = new HashMap<>();
		head.put("serviceName", "getToken");
		Map<String, Object> body = new HashMap<>();
		body.put("userName", "developer");
		body.put("passWord", "F927AAD0CE6684EF36AFCD059F4D5774");
		paramMap.put("head", head);
		paramMap.put("body", body);
		Type maptype = new TypeToken<HashMap<String, Object>>(){}.getType();
		String tokenjson = postjson(paramMap, false, "/p2p-api/getToken");
		HashMap<String, Object> fromJson = gson.fromJson(tokenjson, maptype);
		HashMap<String, Object> fromJson2 = gson.fromJson(fromJson.get("body").toString(), maptype);
		return fromJson2.get("token").toString();
	}

	/**
	 * 发送post请求获取json返回参数
	 * @param paramMap 请求参数
	 * @param needtoken 是否需要token
	 * @param url 请求地址
	 * @return
	 */
	public static String postjson(Object paramMap, boolean needtoken, String url) {
		Gson gson = new Gson();
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost post = new HttpPost(IP+url);
		post.setHeader("Content-Encoding", "utf-8");
		post.setHeader("content-type", "application/json");
		if (needtoken) {
			post.setHeader("Authorization", "Bearer "+getToken());
		}
		StringEntity entity = new StringEntity(gson.toJson(paramMap), Charset.forName("UTF-8"));
		entity.setContentEncoding("UTF-8");
		// 发送Json格式的数据请求
		entity.setContentType("application/json");
		post.setEntity(entity);
		try {
			HttpResponse response = httpclient.execute(post);
			HttpEntity httpEntity = response.getEntity();
			return EntityUtils.toString(httpEntity, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (post != null) {
				post.releaseConnection();
			}
		}
		return null;
	}
}
